using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using Book_Shop.DAL.DAO;

namespace Book_Shop.DAL.Gateway
{
    public class BookGateway:DbGateway  
    {

        public List<Book> GetAll()
        {
            string query = "SELECT * FROM Book Order BY Title Asc";
            List<Book> books = new List<Book>();
            Command.CommandText = query;
            Connection.Open();
            using(SqlDataReader dataReader = Command.ExecuteReader())
            {
                while(dataReader.Read())
                {
                    var book = GetABookInstanceFromAllDataField(dataReader);
                    books.Add(book);
                }
            }
            return books;
        }

        private Book GetABookInstanceFromAllDataField(SqlDataReader inDataReader)
        {
            SqlDataReader dataReader = inDataReader;
            Book book = new Book();
            book.Id = int.Parse(dataReader["Id"].ToString());
            book.Author = dataReader["Author"].ToString();
            book.Title = dataReader["Title"].ToString();
            book.ISBN = dataReader["ISBN"].ToString();
            book.Publisher = dataReader["Publisher"].ToString();
            book.UnitPrice = double.Parse(dataReader["UnitPrice"].ToString());
            book.Category = dataReader["Category"].ToString();
            return book;
        }

        public Book GetById(int id)
        {
            string query = "SELECT * FROM Book WHERE Id =@id";
            Command.CommandText = query;
            Command.Parameters.Add("@id", SqlDbType.Int);
            Command.Parameters["@id"].Value = id;
            Connection.Open();
            Book book = new Book();
            using (SqlDataReader dataReader = Command.ExecuteReader())
            {
                while (dataReader.Read())
                {
                    book = GetABookInstanceFromAllDataField(dataReader);
                }
            }
            Connection.Close();
            if (book == null)
            {
                throw new Exception("Book Not Found! : System could not find your book");
            }
            return book;
        }
    }
}